package control

import (
	"WeChatMGRA/modul"
	"WeChatMGRA/requests"
	"WeChatMGRA/server/smodul"
	"encoding/json"
	"gitee.com/yutiandou/wdtools/wdevent"
	"gitee.com/yutiandou/wdtools/wdlog"
	"gitee.com/yutiandou/wdtools/wdutil"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strconv"
	"sync"
	"time"
)

var RobotList = smodul.NewRobotManage()

//AddRobot ..添加机器人 
func AddRobot (g * gin.Context){
	robot := &smodul.Robots{
		Wcid:           g.PostForm("wcid"),
		Creator:        g.PostForm("creator"),
		NickName:       g.PostForm("nickName"),
		TransmitHash:   "",
		CurrentOwner:   "",
		CurrentGroup:   "",
		MaxGroups:      0,
		StartTime:      0,
		WorkTime:       0,
		WorkStat:       1,
		Stat:           1,
		AllLiveGroups:  "",
		LiveGroupsWcid: sync.Map{},
		CurrentListWcid:sync.Map{},
		Online:1,
	}
	if len(robot.Wcid)<5{
		g.JSON(400,"操作错误，请重新添加")
	}
	if robot.InsertRobot() {
		g.JSON(200,"机器人添加成功")
		record := smodul.NewRecord(robot.ID,robot.NickName,robot.Creator,"添加机器人")
		if err:= record.Insert();wdlog.Error(err){
		}
	}else{
		g.JSON(400,"机器人添加失败")
	}
}


type ConfigRobot_Resp struct {
	ID uint `json:"id"`
	MaxGroup int `json:"maxgroups"`
	WorkTime int `json:"worktime"`
	WorkStat int `json:"workstat"`
}

//ConfigRobot 配置机器人开始工作
func ConfigRobot(g * gin.Context) {

	body, _ := ioutil.ReadAll(g.Request.Body)
	cresp := new(ConfigRobot_Resp)
	if err := json.Unmarshal(body, cresp); wdlog.Error(err) {
		g.JSON(403, "参数错误")
		return
	}
	robot := new(smodul.Robots)
	robot.ID = cresp.ID
	if wdlog.Error(robot.Select(1)) {
		g.JSON(400, "当前机器人正在工作，请刷新后使用其他机器人")
		return
	}
	robot.TransmitHash = wdutil.NewRandomId()
	robot.MaxGroups = (cresp.MaxGroup + 1)
	robot.CurrentGroup = "wu"
	robot.StartTime = time.Now().Unix()
	robot.WorkTime = (int64(cresp.WorkTime)) * 3600
	robot.WorkStat = cresp.WorkStat
	robot.NowGroups = 1
	robot.WorkProgress = 1
	robot.Online = 2
	robot.AllLiveGroups = ";"
	robot.CurrentOwner = ";"
	robot.LiveGroupsWcid = sync.Map{}
	robot.CurrentListWcid = sync.Map{}
	//if robot.Updata(1) != 1 {
	//	g.JSON(400, "当前机器人已被占用，请刷新后使用其他机器人")
	//	return
	//}
	//WaitList.AddRobot(robot)
	sl := modul.SecondLogin{
		Wcid: robot.Wcid,
		Type: 2,
	}
	requdata, _ := json.Marshal(sl)
	respdata, err := requests.MakeARequest("secondLogin", requdata)
	if wdlog.Error(err) {
		g.JSON(501, "登陆失败")
		return
	}
	slresp := new(modul.SecondLogin_resp)
	msg, err := requests.VerifyWKResp(respdata, slresp)
	if wdlog.Error(err) {
		g.JSON(500, "服务器错误")
		return
	}
	if msg.Code != "1000" {
		g.JSON(501, "请求失效")
	}
	robot.Wid = slresp.WId
	robot.NickName = slresp.NickName
	if robot.Save(1) !=1{
		g.JSON(400,"机器人已被占用，请刷新重试")
		return
	}
	//go robot.TransmitMsg()
	RobotList.AddRobot(robot)
	g.JSON(200, robot.TransmitHash)
	smodul.NewRecord(robot.ID, robot.NickName, robot.TransmitHash, "机器人配置成功")
	wdevent.ExecEvent("RobotConfigSuccess", robot)
	//RobotList.
}

//RobotForcedOffline 强制机器人下线
func RobotForcedOffline(g * gin.Context){
	sid := g.PostForm("id")
	if id,err:=strconv.Atoi(sid); err == nil{
		if RobotList.RobotForcedOffline(uint(id)) == 0{
			g.JSON(200,"机器人id："+sid+" 已强制下线")
		}else{
			g.JSON(400,"机器人id："+sid+" 不在线")
		}
	}else {
		g.JSON(400,"机器人id："+sid+" 错误")
	}
}

//RobotBackOnline 机器人重新上线
func RobotBackOnline(g * gin.Context){
	sid := g.PostForm("id")
	if id,err:=strconv.Atoi(sid); err == nil{
		robot := new(smodul.Robots)
		robot.ID = (uint(id))
		if wdlog.Error(robot.Select(1)) {
			g.JSON(400, "查询失败，请刷新查看")
			return
		}
		robot.StrGroupsToSliGroups()
		sl:= modul.SecondLogin{
			Wcid: robot.Wcid,
			Type: 2,
		}
		requdata,_:= json.Marshal(sl)
		respdata,err:= requests.MakeARequest("secondLogin",requdata)
		if wdlog.Error(err){
			g.JSON(501,"登陆失败")
			return
		}
		resp := new(modul.SecondLogin_resp)
		msg,err:=requests.VerifyWKResp(respdata,resp)
		if wdlog.Error(err){
			g.JSON(500,"服务器错误")
			return
		}
		if msg.Code!="1000"{
			g.JSON(501,"请求失效")
			return
		}
		robot.Wid = resp.WId
		robot.NickName = resp.NickName
		robot.Online = 2
		if robot.Updata(1) !=1{
			g.JSON(400,"机器人id："+sid+" 已上线")
			return
		}
		//go robot.TransmitMsg()
		RobotList.AddRobot(robot)
		g.JSON(200,"机器人id："+sid+" 已上线")
		smodul.NewRecordAndInsert(robot.ID,robot.NickName,robot.Creator,"机器人重新上线")
	}else {
		g.JSON(400,"机器人id："+sid+" 错误")
	}
}
//RobotStatusShow 机器人状态查询
func RobotStatusShow(g * gin.Context){
	sid := g.PostForm("id")
	if id,err:=strconv.Atoi(sid); err == nil{
		robot:= new(smodul.Robots)
		robot.ID = (uint(id))
		robot.Select(1)
		g.JSON(200,robot)
	}else {
		g.JSON(400,"机器人id："+sid+" 状态未更新")
	}
}


type Getallrobots_resp struct {
	Id uint `json:"id"`
	NickName string `json:"nickname"`
	Stat int  `json:"stat"`
}
//GetAllOfflineRobots .. 查询所有机器人
func GetAllOfflineNormalRobots(g *gin.Context){
	rs,err:= smodul.Get_All_Offline_Robots()
	if err!=nil{
		g.JSON(404,err.Error())
	}
	gs := make([]*Getallrobots_resp,0)
	for _,v:=range rs{
		g := new(Getallrobots_resp)
		g.Id = v.ID
		g.NickName = v.NickName
		g.Stat = v.Online
		gs = append(gs,g)
	}
	g.JSON(200,gs)
}